<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col>
        <!--工具栏-->
        <div class="head-container">
          <!-- <div v-if="crud.props.searchToggle">
            <el-autocomplete
              v-model="query.blurry"
              :fetch-suggestions="querySearch"
              placeholder="输入项目名称"
              style="width: 200px;"
              class="filter-item"
              :trigger-on-focus="false"
              @select="handleSelect"
            >
              <template v-slot="{item}">
                <span class="match-item" v-html="item.name" />
              </template>
            </el-autocomplete>
            <date-range-picker v-model="query.startTime" class="date-item" @change="changeDate" />
            <el-select
              v-model="query.enabled"
              clearable
              size="small"
              placeholder="状态"
              class="filter-item"
              style="width: 90px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in enabledTypeOptions"
                :key="item.key"
                :label="item.display_name"
                :value="item.key"
              />
            </el-select>
            <rrOperation />
          </div> -->
          <crudOperation show="" :permission="permission" />
        </div>
        <!--表单渲染-->
        <el-dialog v-if="isRouterAlive" append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="650px">
          <el-form ref="form" :inline="true" :model="form" size="small" label-width="80px">
            <el-form-item label="项目名称" prop="name">
              <!-- <el-input v-model="form.taskname" placeholder="请选择项目名称" /> -->
              <el-autocomplete
                v-model="form.name"
                :fetch-suggestions="taskSearch"
                placeholder="输入项目名称"
                style="width: 183px;"
                class="filter-item"
                :trigger-on-focus="false"
                @select="taskSelect"
              >
                <template v-slot="{item}">
                  <span class="match-item" v-html="item.name" />
                </template>
              </el-autocomplete>
            </el-form-item>
            <!-- <el-form-item label="任务名称" prop="name">
              <el-input v-model="form.name" placeholder="请选择任务名称" />
            </el-form-item> -->
            <!-- <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="form.startDate" style="width:184px;" type="date" placeholder="请输入日期" />
            </el-form-item>
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="form.endDate" style="width:184px;" type="date" placeholder="请输入日期" />
            </el-form-item> -->
            <!-- <el-form-item label="实际日期" prop="actualStartTime">
              <el-date-picker v-model="form.actualStartTime" style="width:184px;" type="date" placeholder="请输入日期" />
            </el-form-item> -->
            <el-form-item label="任务状态" prop="taskStatus">
              <!-- <el-input v-if="form.taskStatus =='1'" placeholder="完结" />
              <el-input v-else placeholder="未完结" /> -->
              <el-select v-model="form.taskStatus" placeholder="任务状态" style="width:184px;">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="填写日期" prop="actualStartTime">
              <el-date-picker v-model="form.actualStartTime" style="width:184px;" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请输入日期" />
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-time-picker v-model="startTime" style="width:184px;" placeholder="请输入日期" format="HH:mm" value-format="HH:mm" @change="clickDate" />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-time-picker v-model="endTime" style="width:184px;" placeholder="请输入日期" format="HH:mm" value-format="HH:mm" @change="clickDate" />
            </el-form-item>
            <el-form-item label="工作时长" prop="workTime">
              <el-input v-model="form.workTime" placeholder="工作时长" />
            </el-form-item>
            <el-form-item label="工作内容" prop="workContent">
              <el-input v-model="form.workContent" type="textarea" />
            </el-form-item>
            <!-- <el-form-item label="任务描述" prop="taskdeScription">
              <el-input v-model="form.taskdeScription" type="textarea" placeholder="任务描述" />
            </el-form-item> -->
            <!-- <el-form-item label="审核人" prop="reviewer">
              <el-input v-model="form.reviewer" placeholder="该项目的开发经理" />
            </el-form-item> -->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
          <el-table-column :selectable="checkboxT" type="selection" width="55" fixed />
          <el-table-column :show-overflow-tooltip="true" prop="name" label="项目名称" />
          <!-- <el-table-column :show-overflow-tooltip="true" prop="taskname" label="任务名称" />
          <el-table-column prop="remark" label="任务描述" />
          <el-table-column :show-overflow-tooltip="true" prop="startDate" width="100" label="开始日期">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.startDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="endDate" width="100" label="结束日期">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.endDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="updateTime" width="100" label="实际开始日期">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="taskStatus" label="任务状态">
            <template slot-scope="scope">
              <span v-if="scope.row.taskStatus == '1'">完结</span>
              <span v-else>未完结</span>
            </template>
          </el-table-column> -->
          <el-table-column :show-overflow-tooltip="true" prop="actualStartTime" width="100" label="填写日期">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.actualStartTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="startTime" width="100" label="开始时间">
            <template slot-scope="scope">
              <span>{{ toHHmmss(scope.row.startTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="endTime" width="100" label="结束时间">
            <template slot-scope="scope">
              <span>{{ toHHmmss(scope.row.endTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="workTime" label="工作时长(小时)" />
          <el-table-column :show-overflow-tooltip="true" prop="workContent" label="工作内容" />
          <el-table-column :show-overflow-tooltip="true" prop="taskStatus" label="是否完结">
            <template slot-scope="scope">
              <span v-if="scope.row.taskStatus == '1'">完结</span>
              <span v-else>未完结</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="createBy" label="填写人" />
          <el-table-column
            v-permission="['admin','user:edit','user:del']"
            label="操作"
            width="115"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <udOperation
                :data="scope.row"
                :permission="permission"
                :stats="scope.row.taskStatus"
                :disabled-dle="scope.row.id === user.id"
              />
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudWorking from '@/api/working-hours/working'
import { isvalidPhone } from '@/utils/validate'
import { getDepts, getDeptSuperior } from '@/api/system/dept'
import { getAll, getLevel } from '@/api/system/role'
import { getAllJob } from '@/api/system/job'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
// import DateRangePicker from '@/components/DateRangePicker'
import { mapGetters } from 'vuex'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import { getDept } from '@/api/system/item'
let userRoles = []
let userJobs = []
const defaultForm = { enabled: 'false', roles: [], jobs: [], dept: { id: null }}
export default {
  name: 'User',
  components: { crudOperation, udOperation, pagination },
  cruds() {
    return CRUD({ title: '工时', url: 'api/taskWork', crudMethod: { ...crudWorking }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['user_status'],
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      height: document.documentElement.clientHeight - 180 + 'px;',
      deptName: '', depts: [], deptDatas: [], jobs: [], level: 3, roles: [],
      defaultProps: { children: 'children', label: 'name', isLeaf: 'leaf' },
      permission: {
        add: ['admin', 'taskWork:add'],
        edit: ['admin', 'taskWork:edit'],
        del: ['admin', 'taskWork:del']
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '完结' },
        { key: 'false', display_name: '未完结' }
      ],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        taskname: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        startdate: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ]
      },
      options: [{
        value: '1',
        label: '完结'
      }, {
        value: '0',
        label: '未完结'
      }],
      isRouterAlive: true,
      startTime: '',
      endTime: ''
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    // this.crud.msg.add = '新增成功，默认密码：123456'
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
    // this.getCurrentMonthFirst();
    // this.getCurrentMonthLast();
  },
  methods: {
    changeDate() {
      this.query.startDate = this.query.startTime[0]
      this.query.endDate = this.query.startTime[1]
    },
    clickDate() {
      if (this.startTime && this.endTime) {
        const start = this.startTime.replace(/:/, '.')
        const end = this.endTime.replace(/:/, '.')
        const count = Math.round((end - start) * 100) / 100
        this.form.workTime = count
        this.isRouterAlive = false
        this.$nextTick(function() {
          this.isRouterAlive = true
        })
        this.form.startTime = Date.parse(this.form.actualStartTime + ' ' + this.startTime + ':00')
        this.form.endTime = Date.parse(this.form.actualStartTime + ' ' + this.endTime + ':00')
      }
    },
    // 搜索框下拉
    taskSearch(queryString, cb) {
      if (queryString.length) {
        getDept({
          name: queryString
        }).then(res => cb(res.content))
      }
    },
    // 点击下拉选项
    taskSelect(item) {
      this.form.name = item.name
      this.form.dept.id = item.id
      this.form.deptId = item.id
    },
    // 搜索框下拉
    querySearch(queryString, cb) {
      if (queryString.length) {
        getDept({
          name: queryString
        }).then(res => cb(res.content))
      }
    },
    // 点击下拉选项
    handleSelect(item) {
      this.query.blurry = item.name
      this.query.id = item.id
    },
    getCurrentMonthFirst() {
      var date = new Date()
      date.setDate(1)
      var month = parseInt(date.getMonth() + 1)
      var day = date.getDate()
      if (month < 10) month = '0' + month
      if (day < 10) day = '0' + day
      this.query.startTime.push(date.getFullYear() + '-' + month + '-' + day)
    },
    getCurrentMonthLast() {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      this.query.startTime.push(year + seperator1 + month + seperator1 + strDate)
    },
    formatDateTime(inputTime) {
      var date = new Date(inputTime)
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? ('0' + m) : m
      var d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      return y + '-' + m + '-' + d
    },
    toHHmmss(data) {
      var s
      var hours = parseInt((data % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      var minutes = parseInt((data % (1000 * 60 * 60)) / (1000 * 60))
      var seconds = (data % (1000 * 60)) / 1000
      s = (hours < 10 ? ('0' + hours) : hours) + ':' + (minutes < 10 ? ('0' + minutes) : minutes) + ':' + (seconds < 10 ? ('0' + seconds) : seconds)
      return s
    },
    changeRole(value) {
      userRoles = []
      value.forEach(function(data, index) {
        const role = { id: data }
        userRoles.push(role)
      })
    },
    changeJob(value) {
      userJobs = []
      value.forEach(function(data, index) {
        const job = { id: data }
        userJobs.push(job)
      })
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initRoles = []
      const initJobs = []
      userRoles.forEach(function(role, index) {
        initRoles.push(role.id)
      })
      userJobs.forEach(function(job, index) {
        initJobs.push(job.id)
      })
      crud.form.roles = initRoles
      crud.form.jobs = initJobs
    },
    deleteTag(value) {
      userRoles.forEach(function(data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      // this.getRoles()
      if (form.id == null) {
        this.getDepts()
      } else {
        this.getSupDepts(form.dept.id)
      }
      this.getRoleLevel()
      // this.getJobs()
      form.enabled = form.enabled.toString()
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.startTime = this.toHHmmss(form.startTime)
      this.endTime = this.toHHmmss(form.endTime)
      this.form.actualStartTime = this.formatDateTime(form.actualStartTime)
      this.getJobs(this.form.dept.id)
      userRoles = []
      userJobs = []
      const roles = []
      const jobs = []
      form.roles.forEach(function(role, index) {
        roles.push(role.id)
        // 初始化编辑时候的角色
        const rol = { id: role.id }
        userRoles.push(rol)
      })
      form.jobs.forEach(function(job, index) {
        jobs.push(job.id)
        // 初始化编辑时候的岗位
        const data = { id: job.id }
        userJobs.push(data)
      })
      form.roles = roles
      form.jobs = jobs
      // superior({ ids: form.id })
      //   .then(d => {
      //     console.log(d)
      //   })
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      // if (!crud.form.dept.id) {
      //   this.$message({
      //     message: '部门不能为空',
      //     type: 'warning'
      //   })
      //   return false
      // } else if (crud.form.jobs.length === 0) {
      //   this.$message({
      //     message: '岗位不能为空',
      //     type: 'warning'
      //   })
      //   return false
      // } else if (crud.form.roles.length === 0) {
      //   this.$message({
      //     message: '角色不能为空',
      //     type: 'warning'
      //   })
      //   return false
      // }
      // crud.form.roles = userRoles
      // crud.form.jobs = userJobs
      return true
    },
    // 获取左侧部门数据
    getDeptDatas(node, resolve) {
      const sort = 'id,desc'
      const params = { sort: sort }
      if (typeof node !== 'object') {
        if (node) {
          params['name'] = node
        }
      } else if (node.level !== 0) {
        params['pid'] = node.data.id
      }
      setTimeout(() => {
        getDepts(params).then(res => {
          if (resolve) {
            resolve(res.content)
          } else {
            this.deptDatas = res.content
          }
        })
      }, 100)
    },
    getDepts() {
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    getSupDepts(deptId) {
      getDeptSuperior(deptId).then(res => {
        const date = res.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        if (data.children) {
          this.buildDepts(data.children)
        }
        if (data.hasChildren && !data.children) {
          data.children = null
        }
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parentNode.id }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 切换部门
    handleNodeClick(data) {
      if (data.pid === 0) {
        this.query.deptId = null
      } else {
        this.query.deptId = data.id
      }
      this.crud.toQuery()
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.user_status[val] + '" ' + data.username + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudWorking.edit(data).then(res => {
          this.crud.notify(this.dict.label.user_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(() => { })
    },
    // 获取弹窗内岗位数据
    getJobs() {
      getAllJob().then(res => {
        this.jobs = res.content
      }).catch(() => { })
    },
    // 获取权限级别
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
      }).catch(() => { })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
 ::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
    height: 30px;
    line-height: 30px;
  }
</style>
